﻿namespace Summoner
{
    using UnityEngine;
    using UnityEditor;
    using System.Linq;
    using System.Collections.Generic;

    [CustomEditor(typeof(AtlasObject))]
    public class AtlasObjectInspector : Editor
    {
        private AtlasObject _target = null;
        private Vector2 _scrollPos = Vector2.zero;
        private Dictionary<string, Texture2D> _name2texture = new Dictionary<string, Texture2D>();

        private void OnEnable()
        {
            if(this._target == null)
            {
                this._target = (AtlasObject)this.target;
                if(this._target.tileSprites.Count == 0)
                {
                    this.GetAllSprites();
                }
            }
        }

        private void GetAllSprites()
        {
            this._target.Init();
            foreach(KeyValuePair<string, Texture2D> kvp in this._name2texture)
            {
                DestroyImmediate(kvp.Value);
            }
            this._name2texture.Clear();
        }

        public override void OnInspectorGUI()
        {
            EditorGUILayout.ObjectField(this._target.SpriteObject, typeof(Object), true);
            if(GUILayout.Button("Refresh"))
            {
                this.GetAllSprites();
                this._target.Name2Sprite.Clear();
            }
            this._scrollPos = GUILayout.BeginScrollView(this._scrollPos, "box");
            for(int i = 0; i < this._target.tileSprites.Count; i++)
            {
                GUILayout.BeginHorizontal("box");
                GUILayout.Label(this._target.tileSprites[i].name);
                if(!this._name2texture.ContainsKey(this._target.tileSprites[i].name))
                {
                    this._name2texture[this._target.tileSprites[i].name] = this.GenerateTextureFromSprite(this._target.tileSprites[i]);
                }
                GUILayout.Label(this._name2texture[this._target.tileSprites[i].name], "box");
                GUILayout.EndHorizontal();
            }
            GUILayout.EndScrollView();
        }

        private Texture2D GenerateTextureFromSprite(Sprite aSprite)
        {
            var rect = aSprite.rect;
            var tex = new Texture2D((int)rect.width, (int)rect.height);
            var data = aSprite.texture.GetPixels((int)rect.x, (int)rect.y, (int)rect.width, (int)rect.height);
            tex.SetPixels(data);
            tex.Apply(true);
            return tex;
        }
    }
}